package com.baidu.health.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

public class FileUpload {
    public String upload(MultipartFile file){
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String originalFilename = file.getOriginalFilename();
        String endpoint = "oss-cn-beijing.aliyuncs.com";
        String accessKeyId = "LTAI5tKyKRssFDKGZb67UKsW";
        String accessKeySecret = "Fx1VCsmDwZlpbe5g05cshovQv1vpzn";
        String bucketName ="create-file";
        //创建OSS实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        String fileName = UUID.randomUUID().toString();
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        // oss中的文件夹名
        String objectName = "test/" + fileName + fileExtension;

        // 创建上传文件的元信息，可以通过文件元信息设置HTTP header(设置了才能通过返回的链接直接访问)。
        //如果不设置，直接访问url会自行下载图片，看各位自己选择
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentType("image/jpg/mp4");

        ossClient.putObject(bucketName, objectName, inputStream,objectMetadata);

        // 关闭OSSClient。
        ossClient.shutdown();

        String url = "http://"+bucketName+"."+endpoint+"/"+objectName;
        return url;
    }
}
